<template>
    <div class="p-15 p-t-0">
        <div class="table-padding orderDialog">
            <el-form :model="modelForm" ref="modelForm" >
                <div>
                    <el-row>
                        <el-col :span="7" >
                            <el-form-item prop="transferOutId" :rules="[{ required: true, message: '请选择调出仓库', trigger: 'blur',type:'number'}]">
                                <div class="el-input el-input-group el-input-group--prepend el-input--medium">
                                    <div class="el-input-group__prepend">调出仓库</div>
                                    <el-select v-model.number="modelForm.transferOutId" placeholder="请选择"
                                               class="w-100p"
                                               :disabled="isEdit"
                                                @change="beforeChange">
                                        <el-option
                                                v-for="item in warehouseList"
                                                :key="item.id"
                                                :label="item.name"
                                                :disabled="item.state && item.state.key!='NORMAL'"
                                                :value="item.id">
                                        </el-option>
                                    </el-select>
                                </div>
                            </el-form-item>
                        </el-col>
                        <el-col :span="7" :offset="1">
                            <el-form-item prop="transferInId" :rules="[{ required: true, message: '请选择调入仓库', trigger: 'blur',type:'number'}]">
                                <div class="el-input el-input-group el-input-group--prepend  el-input--medium">
                                    <div class="el-input-group__prepend">调入仓库</div>
                                    <el-select v-model.number="modelForm.transferInId" :disabled="isEdit" placeholder="请选择" class="w-100p">
                                        <el-option
                                                v-for="item in warehouseList"
                                                :key="item.id"
                                                :label="item.name"
                                                :disabled="item.state && item.state.key!='NORMAL'"
                                                :value="item.id">
                                        </el-option>
                                    </el-select>
                                </div>
                            </el-form-item>
                        </el-col>
                        <el-col :offset="1" :span="8">
                            <el-form-item prop="no" :rules="[]">
                                <div class="el-input el-input-group el-input-group--prepend el-input--medium">
                                    <div class="el-input-group__prepend">调拨日期</div>
                                     <el-date-picker
                                            v-model="modelForm.operateTime"
                                            type="date"
                                            class="w-100p"
                                            placeholder="选择日期"
                                            :readonly="true"
                                            :disabled="isEdit"
                                            >
                                    </el-date-picker>
                                </div>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <div style="height:20px;"></div>
                    <el-form-item  prop="no" :rules="[]">
                        <el-input type="text" v-model="modelForm.remark"  size="medium" :disabled="isEdit" auto-complete="off" placeholder="请输入备注信息">
                            <template slot="prepend">
                                <el-button>备注</el-button>
                            </template>
                        </el-input>
                    </el-form-item>
                </div>
                <div style="color:red;text-align: left">注：请选择调出库仓库后再选择原料</div>
                <div class="orderTable" style="padding-top:10px">
                    <el-form-item class="text-left text-left1" style="margin-bottom: 10px !important;">
                        <el-button type="primary" size="medium" @click="submitForm('modelForm')"><i class="icon icon-baocun"></i> 保存</el-button>
                        <el-button type="success"  size="medium" @click="resetForm('modelForm')"><i class="icon icon-tijiao"></i> 提交并审核</el-button>
                        <el-button type="warning"  size="medium" v-if="modelForm.id"><i class="icon icon-dayin"></i> 打印</el-button>
                        <el-button  type="danger"  size="medium" @click="goBack()"><i class="icon icon-fanhui1"></i> 取消</el-button>
                    </el-form-item>
                    <el-form-item class="text-left text-left5" style="margin-bottom: 10px !important;">
                        <el-button type="warning"  size="medium"><i class="icon icon-dayin"></i> 打印</el-button>
                        <el-button  type="danger"  size="medium" @click="goBack()"><i class="icon icon-fanhui1"></i> 取消</el-button>
                    </el-form-item>

                    <el-table
                            :data="tableData"
                            border
                            show-summary
                            :summary-method="getSummaries"
                            style="width: 100%">
                        <el-table-column
                                type="index"
                                width="50">
                        </el-table-column>
                        <el-table-column
                                width="80">
                            <template  slot-scope="scope">
                                <span class="el-icon-plus" style="cursor: pointer;font-size: 10px;padding-right: 5px" @click="addColumn(scope.$index)"></span>
                                <span class="el-icon-minus" style="cursor: pointer;font-size: 10px;padding-left: 5px" @click="minusColumn(scope.$index)"></span>
                            </template>
                        </el-table-column>
                      <el-table-column
                        prop="code"
                        label="原料编号"
                        width="150">
                        <template  slot-scope="scope">
                          <div style="position: relative">
                            <el-select v-model="scope.row.code" :disabled="isEdit" remote @change="codeChange(scope.$index)"   :remote-method="remoteMethod"
                                       filterable="" placeholder="请输入原料编号">
                              <el-option v-for="(item,index) in material" :key="index"
                                         :label="item.code" :value="item.code">
                                <div style="width:100px;border-bottom:1px solid #c0c0c0;padding:5px 0px">
                                  {{item.value}}
                                </div>
                              </el-option>
                            </el-select>
                            <span class="el-icon-more" @click="handleIconClick(scope.$index)"
                                  style="cursor: pointer;font-size: 10px;padding-right: 5px; position: absolute;right: 10px;top: 40%"></span>
                          </div>
                        </template>
                      </el-table-column>
                        <el-table-column
                                prop="name"
                                label="原料名称"
                                >
                        </el-table-column>
                        <el-table-column
                                prop="spec"
                                label="规格型号"
                                >
                        </el-table-column>
                        <el-table-column prop="unit" label="库存单位"  ></el-table-column>
                        <el-table-column prop="count" label="调拨数量"  >
                            <template  slot-scope="scope">
                                <el-input v-model="scope.row.count" :disabled="isEdit" @focus="printNum" @blur="utils.isNumber(scope.row,'count');isBigCount(scope.row)"  placeholder="0.00"></el-input>
                            </template>
                        </el-table-column>
                        <el-table-column prop="stockCount" label="库存数量" v-if="!isEdit">
                            <template  slot-scope="scope">
                                <span>{{scope.row.stockCount | money}}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="memo" label="备注">
                            <template  slot-scope="scope">
                                <el-input v-model="scope.row.memo" :disabled="isEdit"  placeholder=""></el-input>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </el-form>
        </div>
      <materials-select :isShow="dialogTableVisible" :warehouseId="modelForm.transferOutId" v-on:pushData="getData" v-on:closeDialog="dialogTableVisible=false"></materials-select>
    </div>
</template>
<script>
  import materialsSelect from "@/components/outMaterialsSelect.vue"
    //注意路径
    export default{
        data(){
            return {
                modelForm: {},
                dialogTableVisible:false,
                tableData:[{id:"",no:"",name:"",goods_spec:"", unit:"", count:0, stockCount:"", memo:""}],
                material:[],
                materialIds:new Set([]),
                warehouseList:[],
                loading:false,
                itemActive:"",
                multipleSelection:[],
                treeData:[],
                inputText:"",
              type:"",
                defaultProps: {
                    children: 'children',
                     label: 'label'
                },
                gridData:[],
                cateId:"",
                isEdit:false,
            };
        },
      components: {
        materialsSelect
      },
        created(){
            window.this = this;
            this.initData();
        },
        mounted(){
            if(this.$route.query.type!=null && this.$route.query.type!=""){
                if(this.$route.query.type=="5"){//5 说明是查看
                    $("input").attr("disabled", true);
                    $(".text-left1").css("display","none");
                    $(".text-left5").css("display","block");
                    this.isEdit=true;
                }
            }
        },
        methods: {
          printNum(){
            event.currentTarget.select();
          },
          codeChange(index) {
            console.log(this.material);
            for (var i = 0; i < this.material.length; i++) {
              if (this.material[i].material_no === this.tableData[index].code) {
                this.tableData[index].code = this.material[i].material_no;
                // this.tableData[index].name = this.material[i].name;
                for (var m = 0; m < this.tableData.length; m++) {
                  if (this.material[i].material_id == this.tableData[m].id) {
                    this.$message.info("本次添加含有重复原料");
                    break;
                  }
                }
              }
              this.tableData[index].id = this.material[i].material_id;
              this.tableData[index].name = this.material[i].matrial_name;
              this.tableData[index].code = this.material[i].material_no;
              this.tableData[index].spec = this.material[i].goods_spec;
              this.tableData[index].unit = this.material[i].material_unit;
              this.tableData[index].stockCount = this.material[i].count;
              this.tableData[index].amount = this.material[i].amount;
              this.tableData[index].cost = this.material[i].cost;
              // this.tableData[index].state = this.material[i].state;
              // this.tableData[index].purchaseCount = this.material[i].purchaseCount;
              // this.tableData[index].unit = this.material[i].unit;
              // this.tableData[index].storagePrice = this.material[i].purchaseNewPrice/this.material[i].purchaseCount;
              break;

            }
          },
          remoteMethod(query) {
            if(this.modelForm.transferOutId=="" || this.modelForm.transferOutId==null ){
              this.$message.error("请先选择调出仓库");
              return;
            }
            if (query != '') {
              this.loading = true;
              this.$axios.get("materials/materials/getMaterialsByNameOrCodeForOut?keywords="+query+"&warehouseId="+this.modelForm.transferOutId).then(data=>{
                this.loading = false;
                if(data.status==200){
                  var a=0;
                  var tempData=data.content.materials;
                  if(data.content.materials && data.content.materials.length<0){
                    this.message.error("暂未搜索到数据");
                    return;
                  }
                  for(var j=0;j<tempData.length;j++){
                    tempData[j].value="["+tempData[j].material_no+"]"+tempData[j].matrial_name;
                  }
                  if(data.content.materials && data.content.materials.length>0){
                    for(let i=0;i<data.content.materials.length;i++){
                      a=0;
                      if(this.material && this.tableData && this.tableData.length>0 && this.tableData[0].id){
                        for(let s=0;s<this.material.length;s++){
                          if( this.material[s].material_id==data.content.materials[i].material_id ){
                            a++;
                          }
                        }
                        if(a<=0){
                          if(this.tableData[i].id){
                            console.log(this.material,"o");
                            for(var i=0;i<tempData.length;i++){
                              this.material.push(
                                tempData[i]
                              );
                            }

                          }
                        }
                      }else{
                        console.log("L");
                        this.material=tempData;
                      }
                    }
                  }else {
                    console.log("h");
                    this.material=tempData;
                  }
                }
              });
            } else {
              console.log("55554")
              this.material=[];
            }
          },
          getData(data){
            if(!this.material){
              this.material = [];
            }
            var a=0;
            for(var i=0;i<data.length;i++){
              a=0;

              for(let s=0;s<this.material.length;s++){
                if(this.material[s].id==data[i].material_id){
                  console.log("3");
                  a++;
                }
              }
              if(a<=0){
                console.log("u");
                data[i].value="["+data[i].material_no+"]"+data[i].matrial_name;
                this.material.push(data[i]);
              }
              this.tableData.push({
                id:data[i].material_id,
                code:data[i].material_no,
                name:data[i].matrial_name,
                spec:data[i].goods_spec,
                unit:data[i].material_unit,
                count: '0',
                chuKuPrice:0.00,
                memo: '',
                amount:data[i].amount,
                cost:data[i].cost,
                stockCount:data[i].count
              });
            }
            for(var i=0;i<this.tableData.length;i++){
              if(this.tableData[i].id==''){
                this.tableData.splice(i,1);
              }
            }
            this.dialogTableVisible=false;
          },
            goBack() {
                this.router.go(-1);
            },
            selectGood(){
              this.dialogTableVisible = true;
            },
            beforeChange(val){
                // this.selectGood();
                // this.tableData = [];
                // this.addColumn(0);
            },
        //页面第一次进来获取表单需要的数据
            initData(){
                var id=this.$route.query.id;
                var query="";
                if(id!=null && id!=""){
                    query="?id="+id;
                    this.modelForm.id=id;
                }
                this.$axios.get("stores/transferOrders/create"+query).then(data=>{
                    if(data.status==200){
                      let json = data.content;
                        this.modelForm=data.content.transferOrder;
                        this.modelForm.operateTime=this.moment().format("YYYY-MM-DD");
                        this.warehouseList=data.content.warehouses;
                          // this.StoreOutType=json.StoreOutType;
                          if (id != null && id != "") {
                            this.material=json.materials;
                            for (var i = 0; i < json.detailList.length; i++) {
                              for(var j=0;j<json.materials.length;j++){
                                if(json.detailList[i].materialId==json.materials[j].material_id){
                                  json.detailList[i].stockCount=json.materials[j].count;
                                  json.detailList[i].cost=json.materials[i].cost;
                                  // value.detailList[i].cost=value.materials[j].purchaseCount;
                                }
                              }
                              json.detailList[i].code = json.detailList[i].no;
                              json.detailList[i].price = (json.detailList[i].price * 1).toFixed(2);
                              json.detailList[i].unit = json.detailList[i].unit;
                              json.detailList[i].spec = json.detailList[i].spec;
                              json.detailList[i].id = json.detailList[i].materialId ;
                              json.detailList[i].name = json.detailList[i].name ;
                              json.detailList[i].memo = json.detailList[i].remark ;

                            }
                            this.tableData = json.detailList;
                          }

                    }else{
                        this.$message.error(data.message);
                    }
                })
            },
            addColumn(index){
                if(this.isEdit) {
                    return;
                }
                this.tableData.splice(index+1,0,{id:"",no:"",name:"",goods_spec:"", unit:"", count:0, stockCount:"", memo:""})
            },
            minusColumn(index){
                if(this.isEdit) {
                    return;
                }
                if(this.tableData.length>1){
                    this.tableData.splice(index,1);
                }else{
                    this.$message.info("最少保留一条");
                }
            },
            //列统计
             getSummaries(param) {
                const { columns, data } = param;
                const sums = [];
                columns.forEach((column, index) => {
                    if (index === 0) {
                        sums[index] = '总价';
                        return;
                    }
                    if(index==6){
                        const values = data.map(item => Number(item[column.property]));
                        if (!values.every(value => isNaN(value))) {
                            sums[index] = values.reduce((prev, curr) => {
                            const value = Number(curr);
                            if (!isNaN(value)) {
                                return (prev*1 + curr*1).toFixed(2);
                            } else {
                                return prev;
                            }
                            }, 0);
                            sums[index];
                        } else {
                            sums[index] = 'N/A';
                        }
                    }
                });
                return sums;
            },
            handleIconClick(index){
                if(this.isEdit) {
                   return;
                }
                // if(!this.modelForm.transferOutId || this.modelForm.transferOutId==""){
                //     this.tableData[index].id="";
                //     this.$message.error("请选择调出仓库后再选择原料");
                //     return;
                // }
                this.dialogTableVisible = true;
                this.itemActive = index;
                this.inputText="";
            },
            checkboxInit(row,index){
                if(row.state && row.state!="NORMAL"){
                    return 0;//不可勾选
                }else{
                    return 1;
                }
            },
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            tableClick(){
                this.dialogTableVisible = false;
                if(this.multipleSelection!=null && this.multipleSelection.length>0){
                    for(var i=this.multipleSelection.length-1;i>=0;i--) {
                        var isAdd=true;
                        for(var m=0;m<this.tableData.length;m++){
                            if(this.multipleSelection[i].id==this.tableData[m].id){
                                // isAdd=false;
                                this.$message.info("本次添加含有重复原料");
                                break;
                            }
                        }
                        if(isAdd) {
                            this.addColumn(this.itemActive);
                            this.tableData[this.itemActive + 1].id=this.multipleSelection[i].id;
                            this.tableData[this.itemActive + 1].no = this.multipleSelection[i].no;
                            this.tableData[this.itemActive + 1].name=this.multipleSelection[i].name;
                            this.tableData[this.itemActive + 1].goods_spec=this.multipleSelection[i].goods_spec;
                            this.tableData[this.itemActive + 1].unit=this.multipleSelection[i].unit;
                            this.tableData[this.itemActive + 1].count="0";
                            this.tableData[this.itemActive + 1].price=this.multipleSelection[i].cost;
                            this.tableData[this.itemActive + 1].stockCount=this.multipleSelection[i].count;
                            this.tableData[this.itemActive + 1].memo="";
                        }
                    }
                    if(this.tableData[this.itemActive].id==""){
                        this.tableData.splice(this.itemActive, 1);
                    }
                }
            },
            newLabel(newList){
                if(newList){
                    for(var i=0;i<newList.length;i++){
                        newList[i].label=newList[i].name;
                        if(newList[i].children){
                            this.newLabel(newList[i].children)
                        }
                    }
                }
            },
            isBigCount(item){
                if(item.count*1>item.stockCount*1){
                    item.count=0;
                    this.$message.error("调拨数量不能大于库存数量！");
                }
            },
            submitForm(formName) {
                this.type=1;
                this.validateData(formName);
            },
            resetForm(formName) {
                this.type=2;
                this.validateData(formName);
            },
            validateData(fromName){
                if (this.tableData == null || this.tableData.length == 0) {
                    this.$message.error("请添加单据明细！");
                    return;
                }
                for (var i = 0; i < this.tableData.length; i++) {
                    if (this.tableData[i].id == "") {
                        if (this.tableData.length == 1) {
                            this.$message.error("请添加单据明细！");
                            return;
                        }
                        this.tableData.splice(i, 1);
                        i--;
                    }
                    if(this.tableData[i].count==0){
                        this.$message.error("请检查单据，出库数量不能为0！");
                        return ;
                    }
                }

                if(this.$route.query.type=="4") {//5 说明是查看
                    this.modelForm.id="";
                }
                this.$refs[fromName].validate((valid)=> {
                    if (valid) {
                        if(this.modelForm.transferOutId == this.modelForm.transferInId){
                            this.$message.error("调入仓库不能和调出仓库一致");
                            return;
                        }
                        var data = {};
                        for(var i=0;i<this.warehouseList.length;i++){
                          if(this.modelForm.transferInId==this.warehouseList[i].id){
                            this.modelForm.transferInName=this.warehouseList[i].name;

                          }
                          if(this.modelForm.transferOutId==this.warehouseList[i].id){
                            this.modelForm.transferOutName=this.warehouseList[i].name;

                          }
                        }
                        data.type=this.type;
                        data.transferOrders = this.modelForm;
                        console.log(this.tableData);
                        var tempData=[];
                        for(var i=0;i<this.tableData.length;i++){
                          tempData.push({
                            materialId:this.tableData[i].id,
                            no:this.tableData[i].code,
                            name:this.tableData[i].name,
                            spec:this.tableData[i].spec,
                            unit:this.tableData[i].unit,
                            count:this.tableData[i].count,
                            price:this.tableData[i].cost,
                            remark:this.tableData[i].memo
                          })
                        }
                        data.details = tempData;
                        this.$axios.post("stores/transferOrders/create", data, "json").then(data=> {
                            if (data.status == 200) {
                                this.$message({
                                    message: data.message,
                                    type: 'success'
                                });
                                this.$emit('addSuccess');
                               this.router.push({path:"/transferOrders"})
                            } else {
                                this.$message.error(data.message);
                            }
                        })
                    } else {
                        this.$message.error("请检查输入项");
                        return false;
                    }
                });
            }
        },

    }
</script>
<style scoped>
    .el-form-item{
        margin-bottom: 0px !important;
    }
    .el-table tr{
        border-bottom: 1px solid #dfe6ec !important;
    }
    .text-left5{display: none;}
</style>
